<template>
  <div class="home-container">
    <div class="top">
      <h2>科室文件存储系统</h2>
      <button class="logout-btn" @click="logout">退出登录</button>
    </div>
    <div class="action-bar">
      <div class="search-container">
        <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索文件名称..."
          class="search-input"
        >
      </div>
      <!-- <button class="logout-btn" @click="logout">退出登录</button> -->
    </div>
    <div class="main-content">
      <FileList :files="filteredFiles" @fileDeleted="handleFileDeleted" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useDepartmentsStore } from '../stores/departments'
import { useRouter } from 'vue-router'
import FileList from '@/components/FileList.vue';

const router = useRouter()

const departmentsStore = useDepartmentsStore()
const searchQuery = ref('')

departmentsStore.setCurrentDepartment(null)

// 处理文件删除事件
const handleFileDeleted = (id) => {
  console.log('HomeView: 文件已删除，ID:', id);
  // 调用store中的方法更新数据
  departmentsStore.fetchFiles();
}

// 退出登录函数
const logout = () => {
  // 清除登录状态
  localStorage.removeItem('isLoggedIn')
  // 触发storage事件，通知App.vue更新状态
  window.dispatchEvent(new StorageEvent('storage', {
    key: 'isLoggedIn',
    oldValue: 'true',
    newValue: null,
    storageArea: localStorage
  }))
  // 重定向到登录页面
  router.push('/login')
}

// 计算属性：根据搜索词过滤文件
const filteredFiles = computed(() => {
  // 获取所有文件 (当currentDepartment为null时，filteredFiles返回所有文件)
  const allFiles = departmentsStore.filteredFiles
  if (!searchQuery.value) {
    return allFiles
  }
  return allFiles.filter(file =>
    file.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})
</script>

<style scoped>
.home-container {
  width: 100%;
  padding: 20px;
}

.top {
  display: flex;
  border-bottom: 2px solid #42b983;
  margin-bottom: 30px;
}

h2 {
  text-align: center;
  color: #333;
  margin: auto;
  font-size: 24px;
  padding-bottom: 0.5rem;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 1.5rem;
  gap: 15px;
}

.logout-btn {
  padding: 8px 16px;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.logout-btn:hover {
  background-color: #c0392b;
}

.search-container {
  display: flex;
  flex: 1;
  max-width: 400px;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}
</style>
